package edu.hm.swe2;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

import edu.hm.swe2.domain.Lagergut;

public class LagergutDAO {

	private EntityManager emgr = 
		Persistence.createEntityManagerFactory("jpademo").createEntityManager();
	
	public void create(Lagergut lg) {

		emgr.getTransaction().begin();
	
		emgr.persist(lg);
		
		emgr.getTransaction().commit();

	}
	
	public Lagergut read(int id) {
		
		emgr.getTransaction().begin();
	
		TypedQuery<Lagergut> tq =
			emgr.createQuery(
					"select object(l) from Lagergut l where l.id = ?1", 
					Lagergut.class);
		tq.setParameter(1, id);
			
		List<Lagergut> result = tq.getResultList();
		
		emgr.getTransaction().commit();
		
		if(result.isEmpty()) return null;
		else return result.get(0);
	}

	public List<Lagergut> findByArtikel(String artikel) {
		
		emgr.getTransaction().begin();
	
		TypedQuery<Lagergut> tq =
			emgr.createQuery(
					"select object(l) from Lagergut l where l.artikel = ?1", 
					Lagergut.class);
		tq.setParameter(1, artikel);
			
		List<Lagergut> result = tq.getResultList();
		
		emgr.getTransaction().commit();
		
		return result;
	}

	
	
	public void update(Lagergut lg) {

		emgr.getTransaction().begin();
		
		emgr.merge(lg);
		
		emgr.getTransaction().commit();

	}
	
	public void delete(Lagergut lg) {
		
		emgr.getTransaction().begin();
		
		emgr.remove(lg);
		
		emgr.getTransaction().commit();
	}
}
